package com.qire.other.share;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;

/**
 * 分享行为具体实现的封装
 */
public abstract class ShareActionImpl implements ShareAction<ShareActionImpl>, PlatformActionListener {

	private ShareErrorListener shareErrorListener;
	private ShareCancelListener shareCancelListener;
	private ShareCompleteListener shareCompleteListener;

	protected abstract ShareParams createShareParams(ShareParams shareParams, HashMap<String, Object> shareMap);
	protected abstract Platform createPlatform();

	protected void fillShareParams(ShareParams shareParams, HashMap<String, Object> shareMap, String keyName){
		Object shareParam = shareMap.get(keyName);
		if(shareParam != null) {
			shareParams.set(keyName, shareParam);
		}
	}

	@Override
	public boolean doShareAction(HashMap<String, Object> shareMap) {
		ShareParams shareParams = new ShareParams();
		createShareParams(shareParams,shareMap);
		Platform platform = createPlatform();
		platform.setPlatformActionListener(this);
		platform.share(shareParams);
		return false;
	}

	@Override
	public ShareActionImpl setShareOnErrorListener(ShareErrorListener shareErrorListener) {
		this.shareErrorListener = shareErrorListener;
		return this;
	}

	@Override
	public ShareActionImpl setShareOnCancelListener(ShareCancelListener shareCancelListener) {
		this.shareCancelListener = shareCancelListener;
		return this;
	}

	@Override
	public ShareActionImpl setShareOnCompleteListener(ShareCompleteListener shareCompleteListener) {
		this.shareCompleteListener = shareCompleteListener;
		return this;
	}

	@Override
	public ShareActionImpl setShareActionListener(ShareActionListener shareActionListener) {
		this.shareErrorListener = shareActionListener;
		this.shareCancelListener = shareActionListener;
		this.shareCompleteListener = shareActionListener;
		return this;
	}

	/**
	 * 平台分享失败回调
	 * @param platform 平台信息（微信、qq或其他）
	 * @param actionCode 错误代码，
	 * @param throwableMsg 异常信息
	 */
	@Override
	public void onError(Platform platform, int actionCode, Throwable throwableMsg) {
		//失败的回调，arg:平台对象，arg1:表示当前的动作，arg2:异常信息
		if(shareErrorListener != null) {
			shareErrorListener.onShareError();
		}
	}

	@Override
	public void onCancel(Platform platform, int actionCode) {
		//取消分享的回调
		if(shareCancelListener != null) {
			shareCancelListener.onShareCancel();
		}
	}
	
	@Override
	public void onComplete(Platform platform, int actionCode, HashMap<String, Object> arg2) {
		//分享成功的回调
		if(shareCompleteListener != null) {
			shareCompleteListener.onShareComplete();
		}
	}

	protected void onComplete() {
		// 微信回调无法判断是否分享故简单统一处理。
		if(shareCompleteListener != null) {
			shareCompleteListener.onShareComplete();
		}
	}

}
